<template lang="">
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区 -->
        <el-card class="rolesList">
            <div>
                <el-button type="primary" style="margin-bottom:20px" @click="addDialogVisibleRoles=true">添加角色
                </el-button>
                <el-table :data="rolesList" style="width: 100%" border stripe>
                    <el-table-column type="expand" width="40">
                        <template slot-scope="{row}">
                            <el-row v-for="(i1,index) in row.children" :key="i1.id"
                                :class="['bdbottom',index==0?'bdtop':'','vcenter']">
                                <!-- 一级权限 -->
                                <el-col :span="5">
                                    <el-tag closable @close="removeRightById(row,i1.id)">
                                        {{i1.authName}}
                                    </el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 2,3级权限 -->
                                <el-col :span="19">
                                    <el-row v-for="(i2,index2) in i1.children" :key="i2.id"
                                        :class="[index2==0?'':'bdtop','vcenter']">
                                        <el-col :span="6">
                                            <el-tag type="success" closable @close="removeRightById(row,i2.id)">
                                                {{i2.authName}}
                                            </el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <el-col :span="18">
                                            <el-tag closable @close="removeRightById(row,i3.id)" type="warning"
                                                v-for=" (i3,index3) in i2.children " :key="i3.id">
                                                {{i3.authName}}
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>

                        </template>
                    </el-table-column>
                    <el-table-column type="index" width="50">
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色名称" width="200">
                    </el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述" width="300">
                    </el-table-column>
                    <el-table-column label="操作" width="width">
                        <template slot-scope="{row}">

                            <el-button type="primary" class="el-icon-edit" size="mini" @click="editRolesInfo(row.id)">
                                编辑
                            </el-button>
                            <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteRoles(row.id)">删除
                            </el-button>
                            <el-button type="warning" class="el-icon-menu" size="mini" @click="showSetRigthDialog(row)">
                                分配权限
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        <!-- 添加的Dialog -->
        <el-dialog title="提示" :visible.sync="addDialogVisibleRoles" width="30%">
            <el-form ref="addFormRef" label-width="70px" :model="addForm">
                <el-form-item label="角色名称">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="addForm.roleDesc"> </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisibleRoles = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑的Dialog -->
        <el-dialog title="编辑信息" :visible.sync="editDialogVisible" width="30%">
            <el-form ref="editFormRef" label-width="70px" :model="editForm">
                <el-form-item label="角色名称">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="editForm.roleDesc"> </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoleList">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%" @close="setRightClose">
            <!-- 树形控件 -->
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defkeys" ref="treeRef"></el-tree>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        name: 'Roles',
        data() {
            return {
                rolesList: [],
                addDialogVisibleRoles: false,
                editDialogVisible: false,
                setRightDialogVisible: false,
                addForm: {
                    roleName: '',
                    roleDesc: ''
                },
                editForm: {
                    roleName: '',
                    roleDesc: ''
                },
                rightsList: [],
                //树形控件的属性绑定对象
                treeProps: {
                    label: 'authName',
                    children: 'children',
                },
                defkeys: [],
                roleId: ''
            }
        },
        created() {
            this.getRolesList()

        },

        methods: {
            async getRolesList() {
                let { data: res } = await this.$http.get('/roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取信息失败')
                }
                this.rolesList = res.data
            },
            //添加角色功能
            async addRoles() {
                let { data: res } = await this.$http.post('roles', { roleName: this.addForm.roleName, roleDesc: this.addForm.roleDesc })
                if (res.meta.status !== 201) {
                    return this.$message.error('添加失败')
                }
                this.$message.success('添加成功')
                this.getRolesList()

                this.addDialogVisibleRoles = false
            },
            //编辑角色功能
            async editRolesInfo(id) {
                let { data: res } = await this.$http.get(`roles/${id}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('编辑失败')
                }

                this.editForm = res.data
                this.editDialogVisible = true
            },
            //提交编辑
            async editRoleList() {
                let { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, {
                    roleName: this.editForm.roleName,
                    roleDesc: this.editForm.roleDesc,
                })
                if (res.meta.status !== 200) {
                    return this.$message.error('修改失败')
                }
                this.$message.success('修改成功')
                this.getRolesList()
                this.editDialogVisible = false
            },
            //删除角色
            async deleteRoles(id) {
                let deleteRes = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (deleteRes === 'cancel') {
                    return this.$message.info('已取消删除')
                }
                let { data: res } = await this.$http.delete(`roles/${id}`)
                console.log(res);
                console.log(this.editForm.roleId);
                if (res.meta.status !== 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.getRolesList()
            },
            //根据ID删除权限
            async removeRightById(roleId, rightId) {
                let removeRes = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (removeRes !== 'confirm') {
                    return this.$message.info('已取消')
                }
                let { data: res } = await this.$http.delete(`roles/${roleId.id}/rights/${rightId}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('取消权限失败')
                }
                roleId.children = res.data
            },
            //分配权限的对话框
            async showSetRigthDialog(row) {
                let { data: res } = await this.$http.get('rights/tree ')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取权限失败')
                }
                this.rightsList = res.data
                this.getLeafKeys(row, this.defkeys)
                this.roleId = row.id
                this.setRightDialogVisible = true
            },
            // 通过递归获取所有的三级权限 ID
            getLeafKeys(node, arr) {
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(item => {
                    this.getLeafKeys(item, arr)
                })
            },
            setRightClose() {
                this.defkeys = []
            },
            //分配权限
            async setRights() {
                const keys = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys(),
                ]
                const idStr = keys.join(',')
                let { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
                if (res.meta.status !== 200) {
                    return this.$message.error('更新失败')
                }
                this.getRolesList()
                this.$message.success('更新成功')
                this.setRightDialogVisible = false
            }

        },
    }
</script>
<style lang="less" scoped>
    .rolesList {
        margin-top: 20px;
    }

    .el-tag {
        margin: 10px;
    }

    .bdtop {
        border-top: 1px solid #ccc;
    }

    .bdbottom {
        border-bottom: 1px solid #ccc;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>